package com.mdnote.practice.linked_list;

import java.util.LinkedList;

/**
 * @author Rhythm-2019
 * @date 2020/10/4
 * @description 联表相加
 */
public class LeetCode2 {

    public static void main(String[] args) {
        LeetCode2 leetCode2 = new LeetCode2();
        ListNode listNode1 = new ListNode(4);
        listNode1.next = new ListNode(2);
        listNode1.next.next = new ListNode(2);

        ListNode listNode2 = new ListNode(3);
        listNode2.next = new ListNode(2);
        listNode2.next.next = new ListNode(1);
        ListNode listNode = leetCode2.addTwoNumbers(listNode1, listNode2);

        ListNode cur = listNode;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 暴力
        ListNode t1 = l1, t2 = l2, head_next = null, head = null;
        boolean flag = false;
        while (t1 != null || t2 != null) {
            int val = (t1 != null ? t1.val : 0) + (t2 != null ? t2.val : 0) + (flag ? 1 : 0);
            flag = val >= 10;
            ListNode cur = new ListNode(val % 10);
            if (head == null) {
                // head
                head = cur;
                head_next = cur;
            }
            head_next.next = cur;
            head_next = head_next.next;
            if (t1 != null) {
                t1 = t1.next;
            }
            if (t2 != null) {
                t2 = t2.next;

            }
        }
        return head;
    }

    public static class ListNode {
     int val;
     ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }

}
